/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SimpleClient.java
 *
 * Created on 07.08.2011, 16:59:51
 */
package com.tsystems.school.simpleclient;

import com.tsystems.school.utils.Message;
import com.tsystems.school.utils.MessageType;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

/**
 *
 * @author 123
 */
public class MessageBox extends javax.swing.JFrame {

    /** Creates new form SimpleClient */
    private ClientWorker cw;
    private String me = "me";
    private String filePath = "D:\\smth\\";
    private HistoryWriter hwr;
    private Contact contact;
    private String logPath;

    public MessageBox() {

        initComponents();

    }

    MessageBox(ClientWorker cw) {
        try {
            UIManager.setLookAndFeel(
                    UIManager.getSystemLookAndFeelClassName());
            this.cw = cw;
            //this.contact = cw.getContact();
            logPath = filePath + contact.getLogin() + ".txt";
            hwr = new HistoryWriter(logPath);
            initComponents();

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MessageBox.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(MessageBox.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(MessageBox.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(MessageBox.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    
    class HistoryWriter {

        private String path;
        private PrintWriter output;
        public HistoryWriter(String path) {
            this.path = path;
            try {
                output = new PrintWriter(new FileWriter(path, true));
            } catch (IOException ex) {
                Logger.getLogger(MessageBox.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        public void writeMessage(String sender, String msg, Date date) {
            String user = sender + " [" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "]" + ": \n";
            if (output == null) {
                    try {
                        output = new PrintWriter(new FileWriter(path, true));
                    } catch (IOException ex) {
                        Logger.getLogger(MessageBox.class.getName()).log(Level.SEVERE, null, ex);
                    }
            } 
            output.println(user);
            output.println(msg);
        }
        
        public void endWriting() {
            if (output != null) 
                output.close();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPane2 = new javax.swing.JTextPane();
        jButton1 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        messagePane = new javax.swing.JTextPane();
        historyButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jScrollPane2.setViewportView(jTextPane2);

        jButton1.setLabel("Отправить");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        messagePane.setEditable(false);
        jScrollPane3.setViewportView(messagePane);

        historyButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/tsystems/school/simpleclient/history.gif"))); // NOI18N
        historyButton.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        historyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                historyButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(historyButton)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(historyButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton1.getAccessibleContext().setAccessibleName("sendBut");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String msg = jTextPane2.getText();
        Date date = new Date();
        addMessagePane("me", msg + "\n", Color.BLUE, date);
        hwr.writeMessage("me", msg, date);
        cw.sendMessage(new Message("", "smb", MessageType.MESSAGE, msg));
    }//GEN-LAST:event_jButton1ActionPerformed

    private void historyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_historyButtonActionPerformed
        System.out.println("pressed");
        hwr.endWriting();

        HistoryForm hf  = new HistoryForm(logPath, contact.getLogin());
        hf.setVisible(true);
    }//GEN-LAST:event_historyButtonActionPerformed

    public HistoryWriter getHistoryWriter() {
        return hwr;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MessageBox().setVisible(true);
            }
        });
    }

    public void setMessagePane(String str) {

        messagePane.setText(str);
    }

    public void addMessagePane(String sender, String str, Color clr, Date date) {
        //messagePane.setText(messagePane.getText() + str);
        String user = sender + " [" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "]" + ": \n";
        StyledDocument doc = messagePane.getStyledDocument();
        Style style = messagePane.addStyle("Blue", null);
        StyleConstants.setForeground(style, Color.blue);
        try {
            StyleContext sc = StyleContext.getDefaultStyleContext();
            AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
                    StyleConstants.Foreground, clr);
            doc.insertString(doc.getLength(), user, aset);
            aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
                    StyleConstants.Foreground, Color.DARK_GRAY);
            doc.insertString(doc.getLength(), str + "\n", aset);
            messagePane.setCaretPosition(doc.getLength());
        } catch (BadLocationException e) {
            // TODO
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton historyButton;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextPane jTextPane2;
    private javax.swing.JTextPane messagePane;
    // End of variables declaration//GEN-END:variables
}
